<template>
  <div class="order-detail-page">
    <!-- 顶部导航栏 -->
    <Header />
    
    <div class="main-content">
      <div class="container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
          <a-breadcrumb>
            <a-breadcrumb-item>
              <a @click="goHome">{{ $t('nav.home') }}</a>
            </a-breadcrumb-item>
            <a-breadcrumb-item>
              <a @click="goToOrders">{{ $t('nav.orders') }}</a>
            </a-breadcrumb-item>
            <a-breadcrumb-item>订单详情</a-breadcrumb-item>
          </a-breadcrumb>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <a-spin size="large" />
          <p>正在加载订单详情...</p>
        </div>
        
        <!-- 订单详情 -->
        <div v-else-if="orderDetail" class="order-detail">
          <!-- 订单状态 -->
          <div class="order-status-card">
            <div class="status-header">
              <div class="status-info">
                <h2>{{ getOrderStatusText(orderDetail.status) }}</h2>
                <p>{{ getOrderStatusDescription(orderDetail.status) }}</p>
              </div>
              <div class="status-icon">
                <CheckCircleOutlined v-if="orderDetail.status === 'completed'" />
                <ClockCircleOutlined v-else-if="orderDetail.status === 'pending'" />
                <CarOutlined v-else-if="orderDetail.status === 'shipped'" />
                <UserOutlined v-else />
              </div>
            </div>
          </div>
          
          <!-- 订单信息 -->
          <div class="order-info-card">
            <h3>订单信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">订单号：</span>
                <span class="value">{{ orderDetail.id }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间：</span>
                <span class="value">{{ formatDate(orderDetail.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">支付时间：</span>
                <span class="value">{{ orderDetail.payTime ? formatDate(orderDetail.payTime) : '未支付' }}</span>
              </div>
              <div class="info-item">
                <span class="label">发货时间：</span>
                <span class="value">{{ orderDetail.shipTime ? formatDate(orderDetail.shipTime) : '未发货' }}</span>
              </div>
              <div class="info-item">
                <span class="label">完成时间：</span>
                <span class="value">{{ orderDetail.completeTime ? formatDate(orderDetail.completeTime) : '未完成' }}</span>
              </div>
              <div class="info-item">
                <span class="label">支付方式：</span>
                <span class="value">{{ orderDetail.paymentMethod || '未选择' }}</span>
              </div>
            </div>
          </div>
          
          <!-- 收货地址 -->
          <div class="address-card">
            <h3>收货地址</h3>
            <div class="address-info">
              <div class="contact-info">
                <span class="name">{{ orderDetail.address.name }}</span>
                <span class="phone">{{ orderDetail.address.phone }}</span>
              </div>
              <div class="address-detail">
                {{ orderDetail.address.province }} {{ orderDetail.address.city }} {{ orderDetail.address.district }}
                {{ orderDetail.address.detail }}
              </div>
            </div>
          </div>
          
          <!-- 商品列表 -->
          <div class="products-card">
            <h3>商品信息</h3>
            <div class="products-list">
              <div v-for="product in orderDetail.products" :key="product.id" class="product-item">
                                  <div class="product-image">
                    <img :src="product.images ? product.images[0] : product.image" :alt="product.name" />
                  </div>
                <div class="product-info">
                  <h4 class="product-name">{{ product.name }}</h4>
                  <p class="product-spec">{{ product.specification }}</p>
                  <div class="product-price">
                    <span class="price">¥{{ product.price }}</span>
                    <span class="quantity">×{{ product.quantity }}</span>
                  </div>
                </div>
                <div class="product-total">
                  ¥{{ (product.price * product.quantity).toFixed(2) }}
                </div>
                <div class="product-actions">
                  <a-button size="small" @click="viewProductDetail(product.id)">
                    查看商品
                  </a-button>
                  <a-button 
                    v-if="orderDetail.status === 'completed'"
                    size="small" 
                    @click="writeReview(product.id)"
                  >
                    评价
                  </a-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 物流信息 -->
          <div v-if="orderDetail.logistics" class="logistics-card">
            <h3>物流信息</h3>
            <div class="logistics-info">
              <div class="logistics-company">
                <span class="label">物流公司：</span>
                <span class="value">{{ orderDetail.logistics.company }}</span>
              </div>
              <div class="logistics-number">
                <span class="label">物流单号：</span>
                <span class="value">{{ orderDetail.logistics.trackingNumber }}</span>
                <a-button size="small" @click="trackLogistics">
                  查看物流
                </a-button>
              </div>
            </div>
            
            <!-- 物流轨迹 -->
            <div class="logistics-timeline">
              <a-timeline>
                <a-timeline-item 
                  v-for="(track, index) in orderDetail.logistics.tracks" 
                  :key="index"
                  :color="index === 0 ? 'green' : 'blue'"
                >
                  <div class="track-item">
                    <div class="track-time">{{ formatDate(track.time) }}</div>
                    <div class="track-content">{{ track.content }}</div>
                  </div>
                </a-timeline-item>
              </a-timeline>
            </div>
          </div>
          
          <!-- 订单金额 -->
          <div class="amount-card">
            <h3>订单金额</h3>
            <div class="amount-details">
              <div class="amount-item">
                <span class="label">商品总额：</span>
                <span class="value">¥{{ orderDetail.subtotal }}</span>
              </div>
              <div class="amount-item">
                <span class="label">运费：</span>
                <span class="value">¥{{ orderDetail.shippingFee }}</span>
              </div>
              <div class="amount-item" v-if="orderDetail.discount">
                <span class="label">优惠金额：</span>
                <span class="value discount">-¥{{ orderDetail.discount }}</span>
              </div>
              <div class="amount-item total">
                <span class="label">实付金额：</span>
                <span class="value">¥{{ orderDetail.totalAmount }}</span>
              </div>
            </div>
          </div>
          
          <!-- 订单操作 -->
          <div class="order-actions-card">
            <div class="actions">
              <a-button @click="goToOrders">
                返回订单列表
              </a-button>
              
              <a-button 
                v-if="orderDetail.status === 'pending'"
                type="primary"
                @click="payOrder"
              >
                立即付款
              </a-button>
              
              <a-button 
                v-if="orderDetail.status === 'pending'"
                danger
                @click="cancelOrder"
              >
                取消订单
              </a-button>
              
              <a-button 
                v-if="orderDetail.status === 'delivered'"
                type="primary"
                @click="confirmReceived"
              >
                确认收货
              </a-button>
              
              <a-button 
                v-if="orderDetail.status === 'completed'"
                @click="buyAgain"
              >
                再次购买
              </a-button>
              
              <a-button 
                v-if="orderDetail.status === 'completed'"
                @click="applyRefund"
              >
                申请退款
              </a-button>
            </div>
          </div>
        </div>
        
        <!-- 订单不存在 -->
        <div v-else class="not-found">
          <ExclamationCircleOutlined class="not-found-icon" />
          <h3>订单不存在</h3>
          <p>该订单可能已被删除或不存在</p>
          <a-button type="primary" @click="goToOrders">
            返回订单列表
          </a-button>
        </div>
      </div>
    </div>
    
    <!-- 底部信息 -->
    <Footer />
    
    <!-- 取消订单确认弹窗 -->
    <a-modal
      v-model:open="showCancelModal"
      title="取消订单"
      @ok="confirmCancelOrder"
    >
      <p>确定要取消这个订单吗？取消后无法恢复。</p>
    </a-modal>
    
    <!-- 确认收货弹窗 -->
    <a-modal
      v-model:open="showConfirmModal"
      title="确认收货"
      @ok="confirmReceivedOrder"
    >
      <p>确认已收到商品吗？确认后将无法申请退款。</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  CarOutlined,
  UserOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'

// 使用Vuex store和Vue Router
const store = useStore()
const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const showCancelModal = ref(false)
const showConfirmModal = ref(false)

// 模拟订单详情数据 - 将通过API获取
const orderDetail = ref(null)

// 方法
const loadOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) return
  
  loading.value = true
  
  try {
    // 这里应该调用API获取订单详情
    // const response = await store.dispatch('order/fetchOrderDetail', orderId)
    // orderDetail.value = response
    
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
  } catch (error) {
    console.error('加载订单详情失败:', error)
    message.error('加载订单详情失败，请重试')
  } finally {
    loading.value = false
  }
}

const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    delivered: '已送达',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getOrderStatusDescription = (status) => {
  const descriptionMap = {
    pending: '请尽快完成支付，超时订单将自动取消',
    paid: '商家正在处理您的订单',
    shipped: '商品正在配送中，请保持手机畅通',
    delivered: '商品已送达，请及时签收',
    completed: '订单已完成，感谢您的购买',
    cancelled: '订单已取消'
  }
  return descriptionMap[status] || ''
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const viewProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

const writeReview = (productId) => {
  message.info('评价功能开发中')
}

const trackLogistics = () => {
  message.info('物流跟踪功能开发中')
}

const payOrder = () => {
  router.push(`/checkout?orderId=${orderDetail.value.id}`)
}

const cancelOrder = () => {
  showCancelModal.value = true
}

const confirmCancelOrder = () => {
  orderDetail.value.status = 'cancelled'
  message.success('订单已取消')
  showCancelModal.value = false
}

const confirmReceived = () => {
  showConfirmModal.value = true
}

const confirmReceivedOrder = () => {
  orderDetail.value.status = 'completed'
  message.success('已确认收货')
  showConfirmModal.value = false
}

const buyAgain = () => {
  // 将订单中的商品添加到购物车
  orderDetail.value.products.forEach(product => {
    store.dispatch('cart/addToCart', {
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.image,
      quantity: product.quantity
    })
  })
  
  message.success('已添加到购物车')
  router.push('/cart')
}

const applyRefund = () => {
  message.info('退款申请功能开发中')
}

const goHome = () => {
  router.push('/')
}

const goToOrders = () => {
  router.push('/orders')
}

// 生命周期
onMounted(() => {
  loadOrderDetail()
})
</script>

<style scoped>
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  flex: 1;
  padding: 20px 0;
}

.breadcrumb {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-container p {
  margin-top: 15px;
  color: #666;
}

.order-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-status-card,
.order-info-card,
.address-card,
.products-card,
.logistics-card,
.amount-card,
.order-actions-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.order-status-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px;
}

.status-info h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 600;
}

.status-info p {
  margin: 0;
  opacity: 0.9;
}

.status-icon {
  font-size: 48px;
  opacity: 0.8;
}

.order-info-card,
.address-card,
.products-card,
.logistics-card,
.amount-card {
  padding: 30px;
}

.order-info-card h3,
.address-card h3,
.products-card h3,
.logistics-card h3,
.amount-card h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  gap: 10px;
}

.info-item .label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.info-item .value {
  color: #333;
}

.address-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.contact-info {
  display: flex;
  gap: 20px;
}

.contact-info .name {
  font-weight: 600;
  color: #333;
}

.contact-info .phone {
  color: #666;
}

.address-detail {
  color: #666;
  line-height: 1.6;
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-item {
  display: flex;
  gap: 15px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  align-items: center;
}

.product-image img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.product-name {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.product-spec {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.product-price {
  display: flex;
  gap: 10px;
  align-items: center;
}

.price {
  font-weight: 600;
  color: #333;
}

.quantity {
  color: #666;
  font-size: 12px;
}

.product-total {
  font-weight: 600;
  color: #333;
  font-size: 16px;
  min-width: 100px;
  text-align: right;
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.logistics-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.logistics-company,
.logistics-number {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logistics-company .label,
.logistics-number .label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.logistics-company .value,
.logistics-number .value {
  color: #333;
}

.logistics-timeline {
  padding: 20px 0;
}

.track-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.track-time {
  font-size: 12px;
  color: #666;
}

.track-content {
  color: #333;
}

.amount-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-item .label {
  color: #666;
}

.amount-item .value {
  color: #333;
  font-weight: 500;
}

.amount-item .value.discount {
  color: #ff4d4f;
}

.amount-item.total {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
  margin-top: 15px;
}

.amount-item.total .label,
.amount-item.total .value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.order-actions-card {
  padding: 30px;
}

.actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.not-found {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.not-found-icon {
  font-size: 64px;
  color: #d9d9d9;
  margin-bottom: 20px;
}

.not-found h3 {
  font-size: 20px;
  color: #333;
  margin: 0 0 10px 0;
}

.not-found p {
  color: #666;
  margin: 0 0 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 15px 0;
  }
  
  .status-header {
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }
  
  .status-icon {
    font-size: 36px;
  }
  
  .order-info-card,
  .address-card,
  .products-card,
  .logistics-card,
  .amount-card,
  .order-actions-card {
    padding: 20px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .product-item {
    flex-direction: column;
    text-align: center;
  }
  
  .product-total {
    text-align: center;
  }
  
  .product-actions {
    flex-direction: row;
    justify-content: center;
  }
  
  .actions {
    flex-direction: column;
  }
  
  .actions .ant-btn {
    width: 100%;
  }
}
</style> 